import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getUserInfo } from '@/api/auth'
import type { ApiResponse, User } from '@/types/api'

interface UserState {
  id: number
  username: string
  role: string
  avatarHash: string
}

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserState>({
    id: 0,
    username: '',
    role: '',
    avatarHash: ''
  })

  // 判断是否为管理员
  const isAdmin = computed(() => userInfo.value.role === 'admin')

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const res = await getUserInfo()
      if (res.code === 200 && res.data) {
        userInfo.value = {
          id: res.data.id || 0,
          username: res.data.username || '',
          role: res.data.role || '',
          avatarHash: res.data.avatarHash || ''
        }
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }

  return {
    userInfo,
    isAdmin,
    fetchUserInfo
  }
}) 